package com.heima.behavior.service.impl;

import com.heima.behavior.dtos.ArticleBehaviorDto;
import com.heima.behavior.service.ApBehaviorServcie;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.pojos.ApUser;
import com.heima.utils.thread.ApTheadLocalUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;

/**
 * @author shitou
 * @className ApBehaviorServcieImpl
 * @description: TODO
 */
@Service
@Slf4j
public class ApBehaviorServcieImpl implements ApBehaviorServcie {
    @Resource
    private StringRedisTemplate stringRedisTemplate;


    /**
     * 加载行为列表
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult loadArticleBehavior(ArticleBehaviorDto dto) {
        log.info("加载行为列表已执行");
        // 校验参数
        if (dto == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        Long articleId = dto.getArticleId();
        if (articleId == null || articleId < 0) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        // 用户未登录
        ApUser apUser = ApTheadLocalUtil.getApUser();
        if (apUser == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        Integer userId = apUser.getId();
        // 游客需要进行登录，才能进行用户行为
        if (userId == 0) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        Long authorId = dto.getAuthorId();
        if (authorId == null || authorId <= 0) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        // 用户行为
        //设置初始化值
        boolean isUnlike = false, isLike = false, isCollection = false, isFollow = false;
        // 查询收藏行为
        String collection_hash_key = "USER_COLLECTION_" + dto.getArticleId();
        isCollection = stringRedisTemplate.opsForHash().hasKey(collection_hash_key, userId + "");

        // 查询点赞行为
        String like_hash_key = "USER_LIKES_" + dto.getArticleId();
        isLike = stringRedisTemplate.opsForHash().hasKey(like_hash_key, userId + "");
        // 查询关注行为
        String userFollowUserId = "USER_FOLLOW_" + apUser.getId();
        isFollow = stringRedisTemplate.opsForHash().hasKey(userFollowUserId, authorId + "");

        // 查询不喜欢行为
        String userUnLikes = "USER_UN_LIKES_" + dto.getArticleId();
        isUnlike = stringRedisTemplate.opsForHash().hasKey(userUnLikes, userId + "");

        HashMap<String, Boolean> map = new HashMap<>();
        map.put("islike", isLike);
        map.put("isunlike", isUnlike);
        map.put("iscollection", isCollection);
        map.put("isfollow", isFollow);
        return ResponseResult.okResult(map);
    }
}
